package top.byfree.jbyan.find.handler.impl;

import top.byfree.jbyan.find.FindApplication;
import top.byfree.jbyan.find.command.Arg;
import top.byfree.jbyan.find.handler.ResultHandler;
import top.byfree.jbyan.find.result.Line;
import top.byfree.jbyan.find.result.ResultSet;

import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jbyan
 * @since 2023/8/4
 */
public class ConsoleResultHandler implements ResultHandler {

    private static final Boolean RESULT_ALL = FindApplication.ARGS.isArg(Arg.RESULT_ALL);

    private static final List<String> POS_ARGS = FindApplication.ARGS.getPosArgs();

    private static final Boolean RESULT_MESSAGE = FindApplication.ARGS.isArg(Arg.RESULT_MESSAGE);

    private static final String[] COLORS = {"\u001B[31m", "\u001B[32m",
            "\u001B[33m", "\u001B[34m", "\u001B[35m", "\u001B[36m"};

    private static final String ANSI_RESET = "\u001B[0m";


    @Override
    public void processor(Path path, List<ResultSet> resultSetTempList) {
        // 未命中，且未指定显示全部结果
        if (!RESULT_ALL && resultSetTempList.size() < 1) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        List<String> collect = resultSetTempList.stream().map(ResultSet::getResult).collect(Collectors.toList());
        sb.append("查询文件：").append(path.toAbsolutePath()).append("，结果：").append(collect).append("\n");
        // 显示命中行信息
        if (RESULT_MESSAGE) {
            for (int i = 0; i < resultSetTempList.size(); i++) {
                sb.append("结果").append(i + 1).append("\n");
                List<Line> resultList = resultSetTempList.get(i).getLines();
                int len = COLORS.length - 1;
                for (Line line : resultList) {
                    String s = line.getIndex() + ": " + line.getLine();
                    for (int j = 0; j < POS_ARGS.size(); j++) {
                        int colorIndex = j % len;
                        String current = POS_ARGS.get(j);
                        s = s.replace(current, colorText(colorIndex, current));
                    }
                    sb.append(s).append("\n");
                }
            }
        }
        System.out.println(sb);

    }

    private String colorText(int i, String text) {
        return COLORS[i] + text + ANSI_RESET;
    }
}
